package com.echo.service.impl;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class EmailService {

    private final JavaMailSender mailSender;
    private final RedisTemplate<String, String> redisTemplate;

    @Value("${spring.mail.username}")
    private String fromEmail;

    public EmailService(JavaMailSender mailSender, RedisTemplate<String, String> redisTemplate) {
        this.mailSender = mailSender;
        this.redisTemplate = redisTemplate;
    }

    public String generateAndSendCaptcha(String toEmail) throws MessagingException {
        // 生成随机 6 位验证码
        String captcha = String.valueOf(new Random().nextInt(900000) + 100000);

        // 存储验证码到 Redis，设置 5 分钟过期
        redisTemplate.opsForValue().set("captcha:" + toEmail, captcha, 5, TimeUnit.MINUTES);

        // 创建 HTML 格式的邮件消息
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(fromEmail);
        helper.setTo(toEmail);
        helper.setSubject("✨ 欢迎加入 Wisdom Cloud ！");

        // 个性化 HTML 内容
        String htmlContent = "<div style='font-family: Arial, sans-serif; color: #333; background-color: #f9f9f9; padding: 20px; border: 1px solid #ddd; border-radius: 8px;'>"
                + "<h1 style='color: #4CAF50;'>🤩 欢迎注册 Wisdom Cloud！</h1>"
                + "<p>嘿，您好！您的验证码是：</p>"
                + "<p style='font-size: 20px; font-weight: bold; color: #FF5722;'>🎉 " + captcha + " 🎉</p>"
                + "<p>请注意验证码的有效时间是： <strong style='color: #03A9F4;'>5 分钟</strong>。</p>"
                + "<p style='font-size: 14px; color: #888;'>如果这不是您本人的操作，请忽略此邮件。</p>"
                + "<p style='margin-top: 20px; font-size: 12px; color: #666;'>💡 Tips：保持您的邮箱安全，避免泄露验证码。</p>"
                + "</div>";

        helper.setText(htmlContent, true); // 第二个参数设置为 true，表示启用 HTML 格式

        // 发送邮件
        mailSender.send(mimeMessage);

        System.out.println("验证码已发送至邮箱：" + toEmail);
        return captcha;
    }
}
